import { _decorator, Component, Node, Graphics, Color, view, game, BlockInputEvents, UITransform } from 'cc'
const { ccclass, property } = _decorator

// 状态
export enum DrawState {
  IDLE = 'IDLE',
  FADE_IN = 'FADE_IN',
  FADE_OUT = 'FADE_OUT',
}

// 获取屏幕尺寸
const WIDTH = view.getVisibleSize().width
const HEIGHT = view.getVisibleSize().height

export const default_duration = 200

@ccclass('DrawManager')
export class DrawManager extends Component {
  private ctx: Graphics | null = null
  private state:DrawState = DrawState.IDLE
  private oldTime: number = 0
  private duration: number = 0
  fadeResolve: (value: any) => void = () => {}
  private blockInput: BlockInputEvents | null = null

  init() {
    this.ctx = this.addComponent(Graphics)
    // 阻断输入
    this.blockInput = this.addComponent(BlockInputEvents)
    this.blockInput.enabled = false
    // 确保节点在屏幕中央，并盖住屏幕
    const transform = this.getComponent(UITransform)
    transform.setAnchorPoint(0.5, 0.5)
    transform.setContentSize(WIDTH, HEIGHT)

   this.setAlpha(1)
  }

  setAlpha(alpha: number) {
    this.ctx.clear()
    this.ctx.rect(0, 0, WIDTH, HEIGHT)
    this.ctx.fillColor = new Color(0, 0, 0, 255*alpha);
    this.ctx.fill();

    this.blockInputEvents(alpha === 1)
  }

  blockInputEvents(block: boolean) {
    this.blockInput.enabled = block
  }

  protected update(dt: number): void {
    let nowTime = game.totalTime
    let time = nowTime - this.oldTime
    const alpha = time / this.duration

    if(this.state === DrawState.FADE_IN) {
      if(alpha >= 1) {
        this.state = DrawState.IDLE
        this.setAlpha(1)
        this.fadeResolve(null)
      } else {
        this.setAlpha(alpha)
      }
    } else if(this.state === DrawState.FADE_OUT) {
      if(alpha >= 1) {
        this.state = DrawState.IDLE
        this.setAlpha(0)
        this.fadeResolve(null)
      } else {
        this.setAlpha(1 - alpha)
      }
    }
  }

  // 淡入
  fadeIn(duration: number=default_duration) {
    this.setAlpha(0)
    this.state = DrawState.FADE_IN
    this.oldTime = game.totalTime
    this.duration = duration
    // 方便进行回调
    return new Promise((resolve, reject) => {
      this.fadeResolve = resolve
    })
  }

  // 淡出
  fadeOut(duration: number=default_duration) {
    this.setAlpha(1)
    this.state = DrawState.FADE_OUT
    this.oldTime = game.totalTime
    this.duration = duration
    // 方便进行回调
    return new Promise((resolve, reject) => {
      this.fadeResolve = resolve
    })
  }

  // 遮罩
  mask(duration: number=default_duration) {
    this.setAlpha(1)
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(null)
      }, duration)
    })
  }
}
